package com.yy.base.common.interceptor;

import java.io.Serializable;
import java.util.Date;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import com.yy.base.common.entity.BaseEntity;
import com.yy.base.util.SessionInfo;

/**
 * 实体拦截
 * 自动保存更新时间更新人,创建时间创建人
 */
@SuppressWarnings("serial")
public class EntityInterceptor extends EmptyInterceptor {
	/**
	 * 更新时
	 */
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if (entity instanceof BaseEntity) {
			BaseEntity base = (BaseEntity)entity;
			base.setUpdated(new Date());
			base.setUpdatedBy(SessionInfo.getUser().getId());
			return true;
		}
		return false;
	}

	/**
	 * 保存时
	 */
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		if (entity instanceof BaseEntity) {
			BaseEntity base = (BaseEntity)entity;
			base.setCreated(new Date());
			base.setCreatedBy(SessionInfo.getUser().getId());
			base.setIsActive(true);
			return true;
		}
		return false;
	}
}
